package cn.zyx.product.service.impl;

import cn.zyx.basic.service.impl.BaseServiceImpl;
import cn.zyx.product.domain.Product;
import cn.zyx.product.domain.ProductDetail;
import cn.zyx.product.mapper.ProductDetailMapper;
import cn.zyx.product.mapper.ProductMapper;
import cn.zyx.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {

    @Autowired
    private ProductDetailMapper productDetailMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void add(Product product) {
        // 保存基本服务信息
        productMapper.save(product);
        // 保存服务详情信息
        ProductDetail detail = product.getDetail();
        detail.setProduct_id(product.getId());
        productDetailMapper.save(detail);
    }

    @Override
    public void update(Product product) {
        ProductDetail detail = product.getDetail();
        if (detail != null){
            detail.setProduct_id(product.getId());
            if (detail.getId() != null){
                productDetailMapper.update(detail);
            }else {
                productDetailMapper.save(detail);
            }
        }
        productMapper.update(product);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 删除服务详情
        productDetailMapper.removeByProductId(id);
        // 删除服务
        productMapper.remove(id);
    }

    @Override
    public ProductDetail getDetailByProductId(Long productId) {
        return productDetailMapper.loadDetailByProductId(productId);
    }

    @Override
    public void onOrOffSale(List<Long> ids, int flag) {
        // 判断是上架还是下架 -- 上架是1 下架是0
        Map<String,Object> map = new HashMap<>();   // 用map相当于我们mapper接口多个参数用@param注解，sql使用key取值
        map.put("ids", ids);
        if (flag == 1){
            // 调整上架时间
            map.put("onsaleTime", new Date());
            productMapper.onSale(map);
        }else {
            // 调整下架时间
            map.put("offsaleTime", new Date());
            productMapper.offSale(map);
        }
    }
}
